import * as React from "react";

interface Props {
  changeCount: () => void;
  reset: () => void;
}

//子组件 用forwardRef包裹 表示可以向该子组件传递ref
const Child = React.forwardRef((props, ref: any) => {
  const [count, setCount] = React.useState<number>(0);

  //暴露给父组件两个方法 changeCount和reset
  React.useImperativeHandle(ref, () => ({
    changeCount: () => {
      setCount(count + 1);
    },
    reset: () => {
      setCount(0);
    },
  }));

  return <div ref={ref}>Count:{count}</div>;
});

//父组件
export default function ImparativeHandle() {
  const inputRef = React.useRef<Props>();
  // 调用子组件暴露给父组件的方法
  const childFunc1 = () => {
    inputRef.current?.changeCount();
  };
  const childFunc2 = () => {
    inputRef.current?.reset();
  };
  return (
    <>
      {/* 此处注意需要将childRef通过props属性从父组件中传给自己 cRef={childRef} */}
      <Child ref={inputRef} />
      <button onClick={childFunc1}>Count+1</button>
      <button onClick={childFunc2}>Reset</button>
    </>
  );
}
